{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hNFsvtsbmMV-",
    "origin_pos": 0
   },
   "source": [
    "#  Sequence to Sequence Learning\n",
    ":label:`sec_seq2seq`\n",
    "\n",
    "###### NOTE: Currently this is still Work in Progress (WIP) as the loss result isn't the same as the one in d2l.ai book. The team will be taking a look at this and updating it whenever possible.\n",
    "\n",
    "As we have seen in :numref:`sec_machine_translation`,\n",
    "in machine translation\n",
    "both the input and output are a variable-length sequence.\n",
    "To address this type of problem,\n",
    "we have designed a general encoder-decoder architecture\n",
    "in :numref:`sec_encoder-decoder`.\n",
    "In this section,\n",
    "we will\n",
    "use two RNNs to design\n",
    "the encoder and the decoder of\n",
    "this architecture\n",
    "and apply it to *sequence to sequence* learning\n",
    "for machine translation\n",
    ":cite:`Sutskever.Vinyals.Le.2014,Cho.Van-Merrienboer.Gulcehre.ea.2014`.\n",
    "\n",
    "Following the design principle\n",
    "of the encoder-decoder architecture,\n",
    "the RNN encoder can\n",
    "take a variable-length sequence as the input and transforms it into a fixed-shape hidden state.\n",
    "In other words,\n",
    "information of the input (source) sequence\n",
    "is *encoded* in the hidden state of the RNN encoder.\n",
    "To generate the output sequence token by token,\n",
    "a separate RNN decoder\n",
    "can predict the next token based on\n",
    "what tokens have been seen (such as in language modeling) or generated,\n",
    "together with the encoded information of the input sequence.\n",
    ":numref:`fig_seq2seq` illustrates\n",
    "how to use two RNNs\n",
    "for sequence to sequence learning\n",
    "in machine translation.\n",
    "\n",
    "\n",
    "![Sequence to sequence learning with an RNN encoder and an RNN decoder.](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/seq2seq.svg)\n",
    ":label:`fig_seq2seq`\n",
    "\n",
    "In :numref:`fig_seq2seq`,\n",
    "the special \"&lt;eos&gt;\" token\n",
    "marks the end of the sequence.\n",
    "The model can stop making predictions\n",
    "once this token is generated.\n",
    "At the initial time step of the RNN decoder,\n",
    "there are two special design decisions.\n",
    "First, the special beginning-of-sequence \"&lt;bos&gt;\" token is an input.\n",
    "Second,\n",
    "the final hidden state of the RNN encoder is used\n",
    "to initiate the hidden state of the decoder.\n",
    "In designs such as :cite:`Sutskever.Vinyals.Le.2014`,\n",
    "this is exactly\n",
    "how the encoded input sequence information\n",
    "is fed into the decoder for generating the output (target) sequence.\n",
    "In some other designs such as :cite:`Cho.Van-Merrienboer.Gulcehre.ea.2014`,\n",
    "the final hidden state of the encoder\n",
    "is also fed into the decoder as\n",
    "part of the inputs\n",
    "at every time step as shown in :numref:`fig_seq2seq`.\n",
    "Similar to the training of language models in\n",
    ":numref:`sec_language_model`,\n",
    "we can allow the labels to be the original output sequence,\n",
    "shifted by one token:\n",
    "\"&lt;bos&gt;\", \"Ils\", \"regardent\", \".\" $\\rightarrow$\n",
    "\"Ils\", \"regardent\", \".\", \"&lt;eos&gt;\".\n",
    "\n",
    "\n",
    "In the following,\n",
    "we will explain the design of :numref:`fig_seq2seq`\n",
    "in greater detail.\n",
    "We will train this model for machine translation\n",
    "on the English-French dataset as introduced in\n",
    ":numref:`sec_machine_translation`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/PlotUtils.java\n",
    "\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Accumulator.java\n",
    "%load ../utils/Animator.java\n",
    "%load ../utils/TrainingChapter9.java\n",
    "%load ../utils/timemachine/Vocab.java\n",
    "%load ../utils/timemachine/RNNModel.java\n",
    "%load ../utils/timemachine/RNNModelScratch.java\n",
    "%load ../utils/timemachine/TimeMachine.java\n",
    "%load ../utils/timemachine/TimeMachineDataset.java\n",
    "%load ../utils/NMT.java\n",
    "%load ../utils/lstm/Encoder.java\n",
    "%load ../utils/lstm/Decoder.java\n",
    "%load ../utils/lstm/EncoderDecoder.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import java.util.stream.*;\n",
    "import ai.djl.modality.nlp.embedding.*;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager(Functions.tryGpu(0));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Aa3Rz8NXmMV_",
    "origin_pos": 3
   },
   "source": [
    "## Encoder\n",
    "\n",
    "Technically speaking,\n",
    "the encoder transforms an input sequence of variable length into a fixed-shape *context variable* $\\mathbf{c}$, and encodes the input sequence information in this context variable.\n",
    "As depicted in :numref:`fig_seq2seq`,\n",
    "we can use an RNN to design the encoder.\n",
    "\n",
    "Let us consider a sequence example (batch size: 1).\n",
    "Suppose that\n",
    "the input sequence is $x_1, \\ldots, x_T$, such that $x_t$ is the $t^{\\mathrm{th}}$ token in the input text sequence.\n",
    "At time step $t$, the RNN transforms\n",
    "the input feature vector $\\mathbf{x}_t$ for $x_t$\n",
    "and the hidden state $\\mathbf{h} _{t-1}$ from the previous time step\n",
    "into the current hidden state $\\mathbf{h}_t$.\n",
    "We can use a function $f$ to express the transformation of the RNN's recurrent layer:\n",
    "\n",
    "$$\\mathbf{h}_t = f(\\mathbf{x}_t, \\mathbf{h}_{t-1}). $$\n",
    "\n",
    "In general,\n",
    "the encoder transforms the hidden states at\n",
    "all the time steps\n",
    "into the context variable through a customized function $q$:\n",
    "\n",
    "$$\\mathbf{c} =  q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T).$$\n",
    "\n",
    "For example, when choosing $q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T) = \\mathbf{h}_T$ such as in :numref:`fig_seq2seq`,\n",
    "the context variable is just the hidden state $\\mathbf{h}_T$\n",
    "of the input sequence at the final time step.\n",
    "\n",
    "So far we have used a unidirectional RNN\n",
    "to design the encoder,\n",
    "where\n",
    "a hidden state only depends on\n",
    "the input subsequence at and before the time step of the hidden state.\n",
    "We can also construct encoders using bidirectional RNNs. In this case, a hidden state depends on\n",
    "the subsequence before and after the time step (including the input at the current time step), which encodes the information of the entire sequence.\n",
    "\n",
    "\n",
    "Now let us implement the RNN encoder.\n",
    "Note that we use an *embedding layer*\n",
    "to obtain the feature vector for each token in the input sequence.\n",
    "The weight\n",
    "of an embedding layer\n",
    "is a matrix\n",
    "whose number of rows equals to the size of the input vocabulary (`vocabSize`)\n",
    "and number of columns equals to the feature vector's dimension (`embedSize`).\n",
    "For any input token index $i$,\n",
    "the embedding layer\n",
    "fetches the $i^{\\mathrm{th}}$ row (starting from 0) of the weight matrix\n",
    "to return its feature vector.\n",
    "Besides,\n",
    "here we choose a multilayer GRU to\n",
    "implement the encoder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public class Seq2SeqEncoder extends Encoder {\n",
    "\n",
    "    private TrainableWordEmbedding embedding;\n",
    "    private GRU rnn;\n",
    "\n",
    "    /* The RNN encoder for sequence to sequence learning. */\n",
    "    public Seq2SeqEncoder(\n",
    "            int vocabSize, int embedSize, int numHiddens, int numLayers, float dropout) {\n",
    "        super();\n",
    "        // Embedding layer\n",
    "        embedding =\n",
    "                TrainableWordEmbedding.builder()\n",
    "                        .optNumEmbeddings(vocabSize)\n",
    "                        .setEmbeddingSize(embedSize)\n",
    "                        .setVocabulary(null)\n",
    "                        .build();\n",
    "        addChildBlock(\"embedding\", embedding);\n",
    "        rnn =\n",
    "                GRU.builder()\n",
    "                        .setNumLayers(numLayers)\n",
    "                        .setStateSize(numHiddens)\n",
    "                        .optReturnState(true)\n",
    "                        .optBatchFirst(false)\n",
    "                        .optDropRate(dropout)\n",
    "                        .build();\n",
    "        addChildBlock(\"rnn\", rnn);\n",
    "    }\n",
    "\n",
    "    /** {@inheritDoc} */\n",
    "    @Override\n",
    "    public void initializeChildBlocks(NDManager manager, DataType dataType, Shape... inputShapes) {\n",
    "        return;\n",
    "    }\n",
    "\n",
    "    @Override\n",
    "    protected NDList forwardInternal(\n",
    "            ParameterStore parameterStore,\n",
    "            NDList inputs,\n",
    "            boolean training,\n",
    "            PairList<String, Object> params) {\n",
    "        NDArray X = inputs.head();\n",
    "        // The output `X` shape: (`batchSize`, `numSteps`, `embedSize`)\n",
    "        X = this.embedding.forward(parameterStore, new NDList(X), training, params).head();\n",
    "        // In RNN models, the first axis corresponds to time steps\n",
    "        X = X.swapAxes(0, 1);\n",
    "\n",
    "        return this.rnn.forward(parameterStore, new NDList(X), training);\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6mjRmv5lmMWA",
    "origin_pos": 6
   },
   "source": [
    "The returned variables of recurrent layers\n",
    "have been explained in :numref:`sec_rnn-concise`.\n",
    "Let us still use a concrete example\n",
    "to illustrate the above encoder implementation.\n",
    "Below\n",
    "we instantiate a two-layer GRU encoder\n",
    "whose number of hidden units is 16.\n",
    "Given\n",
    "a minibatch of sequence inputs `X`\n",
    "(batch size: 4, number of time steps: 7),\n",
    "the hidden states of the last layer\n",
    "at all the time steps\n",
    "(`output` return by the encoder's recurrent layers)\n",
    "are a tensor\n",
    "of shape\n",
    "(number of time steps, batch size, number of hidden units).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Seq2SeqEncoder encoder = new Seq2SeqEncoder(10, 8, 16, 2, 0);\n",
    "NDArray X = manager.zeros(new Shape(4, 7));\n",
    "NDList outputState =\n",
    "        encoder.forward(new ParameterStore(manager, false), new NDList(X), false);\n",
    "\n",
    "NDArray output = outputState.head();\n",
    "System.out.println(output.getShape());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "N8m9-PsEmMWB",
    "origin_pos": 9
   },
   "source": [
    "Since a GRU is employed here,\n",
    "the shape of the multilayer hidden states\n",
    "at the final time step\n",
    "is\n",
    "(number of hidden layers, batch size, number of hidden units).\n",
    "If an LSTM is used,\n",
    "memory cell information will also be contained in `state`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDList state = outputState.subNDList(1);\n",
    "System.out.println(state.size());\n",
    "System.out.println(state.head().getShape());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ejw98QPgmMWC",
    "origin_pos": 12
   },
   "source": [
    "## Decoder\n",
    ":label:`sec_seq2seq_decoder`\n",
    "\n",
    "As we just mentioned,\n",
    "the context variable $\\mathbf{c}$ of the encoder's output encodes the entire input sequence $x_1, \\ldots, x_T$. Given the output sequence $y_1, y_2, \\ldots, y_{T'}$ from the training dataset,\n",
    "for each time step $t'$\n",
    "(the symbol differs from the time step $t$ of input sequences or encoders),\n",
    "the probability of the decoder output $y_{t'}$\n",
    "is conditional\n",
    "on the previous output subsequence\n",
    "$y_1, \\ldots, y_{t'-1}$ and\n",
    "the context variable $\\mathbf{c}$, i.e., $P(y_{t'} \\mid y_1, \\ldots, y_{t'-1}, \\mathbf{c})$.\n",
    "\n",
    "To model this conditional probability on sequences,\n",
    "we can use another RNN as the decoder.\n",
    "At any time step $t^\\prime$ on the output sequence,\n",
    "the RNN takes the output $y_{t^\\prime-1}$ from the previous time step\n",
    "and the context variable $\\mathbf{c}$ as its input,\n",
    "then transforms\n",
    "them and\n",
    "the previous hidden state $\\mathbf{s}_{t^\\prime-1}$\n",
    "into the\n",
    "hidden state $\\mathbf{s}_{t^\\prime}$ at the current time step.\n",
    "As a result, we can use a function $g$ to express the transformation of the decoder's hidden layer:\n",
    "\n",
    "$$\\mathbf{s}_{t^\\prime} = g(y_{t^\\prime-1}, \\mathbf{c}, \\mathbf{s}_{t^\\prime-1}).$$\n",
    ":eqlabel:`eq_seq2seq_s_t`\n",
    "\n",
    "After obtaining the hidden state of the decoder,\n",
    "we can use an output layer and the softmax operation to compute the conditional probability distribution\n",
    "$P(y_{t^\\prime} \\mid y_1, \\ldots, y_{t^\\prime-1}, \\mathbf{c})$ for the output at time step $t^\\prime$.\n",
    "\n",
    "Following :numref:`fig_seq2seq`,\n",
    "when implementing the decoder as follows,\n",
    "we directly use the hidden state at the final time step\n",
    "of the encoder\n",
    "to initialize the hidden state of the decoder.\n",
    "This requires that the RNN encoder and the RNN decoder have the same number of layers and hidden units.\n",
    "To further incorporate the encoded input sequence information,\n",
    "the context variable is concatenated\n",
    "with the decoder input at all the time steps.\n",
    "To predict the probability distribution of the output token,\n",
    "a fully-connected layer is used to transform\n",
    "the hidden state at the final layer of the RNN decoder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public class Seq2SeqDecoder extends Decoder {\n",
    "\n",
    "    private TrainableWordEmbedding embedding;\n",
    "    private GRU rnn;\n",
    "    private Linear dense;\n",
    "\n",
    "    /* The RNN decoder for sequence to sequence learning. */\n",
    "    public Seq2SeqDecoder(\n",
    "            int vocabSize, int embedSize, int numHiddens, int numLayers, float dropout) {\n",
    "        super();\n",
    "        this.embedding =\n",
    "                TrainableWordEmbedding.builder()\n",
    "                        .optNumEmbeddings(vocabSize)\n",
    "                        .setEmbeddingSize(embedSize)\n",
    "                        .setVocabulary(null)\n",
    "                        .build();\n",
    "        this.addChildBlock(\"embedding\", embedding);\n",
    "        this.rnn =\n",
    "                GRU.builder()\n",
    "                        .setNumLayers(numLayers)\n",
    "                        .setStateSize(numHiddens)\n",
    "                        .optReturnState(true)\n",
    "                        .optBatchFirst(false)\n",
    "                        .optDropRate(dropout)\n",
    "                        .build();\n",
    "        this.addChildBlock(\"rnn\", rnn);\n",
    "        this.dense = Linear.builder().setUnits(vocabSize).build();\n",
    "        this.addChildBlock(\"dense\", dense);\n",
    "    }\n",
    "\n",
    "    /** {@inheritDoc} */\n",
    "    @Override\n",
    "    public void initializeChildBlocks(NDManager manager, DataType dataType, Shape... inputShapes) {\n",
    "        return;\n",
    "    }\n",
    "\n",
    "    public NDList initState(NDList encOutputs) {\n",
    "        return new NDList(encOutputs.get(1));\n",
    "    }\n",
    "\n",
    "    @Override\n",
    "    protected NDList forwardInternal(\n",
    "            ParameterStore parameterStore,\n",
    "            NDList inputs,\n",
    "            boolean training,\n",
    "            PairList<String, Object> params) {\n",
    "        NDArray X = inputs.head();\n",
    "        NDArray state = inputs.get(1);\n",
    "        X =\n",
    "                this.embedding\n",
    "                        .forward(parameterStore, new NDList(X), training, params)\n",
    "                        .head()\n",
    "                        .swapAxes(0, 1);\n",
    "        NDArray context = inputs.get(1).get(new NDIndex(-1));\n",
    "        // Broadcast `context` so it has the same `numSteps` as `X`\n",
    "        context =\n",
    "                context.broadcast(\n",
    "                        new Shape(\n",
    "                                X.getShape().head(),\n",
    "                                context.getShape().head(),\n",
    "                                context.getShape().get(1)));\n",
    "        NDArray xAndContext = NDArrays.concat(new NDList(X, context), 2);\n",
    "        NDList rnnOutput =\n",
    "                rnn.forward(parameterStore, new NDList(xAndContext, state), training);\n",
    "        NDArray output = rnnOutput.head();\n",
    "        state = rnnOutput.get(1);\n",
    "        output =\n",
    "                dense\n",
    "                        .forward(parameterStore, new NDList(output), training)\n",
    "                        .head()\n",
    "                        .swapAxes(0, 1);\n",
    "        return new NDList(output, state);\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jZXE4tR_mMWC",
    "origin_pos": 15
   },
   "source": [
    "To illustrate the implemented decoder,\n",
    "below we instantiate it with the same hyperparameters from the aforementioned encoder.\n",
    "As we can see, the output shape of the decoder becomes (batch size, number of time steps, vocabulary size),\n",
    "where the last dimension of the tensor stores the predicted token distribution.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Seq2SeqDecoder decoder = new Seq2SeqDecoder(10, 8, 16, 2, 0);\n",
    "state = decoder.initState(outputState);\n",
    "outputState =\n",
    "        decoder.forward(\n",
    "                new ParameterStore(manager, false), new NDList(X).addAll(state), false);\n",
    "\n",
    "output = outputState.head();\n",
    "System.out.println(output.getShape());\n",
    "\n",
    "state = outputState.subNDList(1);\n",
    "        System.out.println(state.size());\n",
    "        System.out.println(state.head().getShape());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "VwXt2NOvmMWD",
    "origin_pos": 18
   },
   "source": [
    "To summarize,\n",
    "the layers in the above RNN encoder-decoder model are illustrated in :numref:`fig_seq2seq_details`.\n",
    "\n",
    "![Layers in an RNN encoder-decoder model.](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/seq2seq-details.svg)\n",
    ":label:`fig_seq2seq_details`\n",
    "\n",
    "## Loss Function\n",
    "\n",
    "At each time step, the decoder\n",
    "predicts a probability distribution for the output tokens.\n",
    "Similar to language modeling,\n",
    "we can apply softmax to obtain the distribution\n",
    "and calculate the cross-entropy loss for optimization.\n",
    "Recall :numref:`sec_machine_translation`\n",
    "that the special padding tokens\n",
    "are appended to the end of sequences\n",
    "so sequences of varying lengths\n",
    "can be efficiently loaded\n",
    "in minibatches of the same shape.\n",
    "However,\n",
    "prediction of padding tokens\n",
    "should be excluded from loss calculations.\n",
    "\n",
    "To this end,\n",
    "we can use the following\n",
    "`sequenceMask` function\n",
    "to mask irrelevant entries with zero values\n",
    "so later\n",
    "multiplication of any irrelevant prediction\n",
    "with zero equals to zero.\n",
    "For example,\n",
    "if the valid length of two sequences\n",
    "excluding padding tokens\n",
    "are one and two, respectively,\n",
    "the remaining entries after\n",
    "the first one\n",
    "and the first two entries are cleared to zeros.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = manager.create(new int[][] {{1, 2, 3}, {4, 5, 6}});\n",
    "System.out.println(X.sequenceMask(manager.create(new int[] {1, 2})));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LVTiJyndmMWD",
    "origin_pos": 21
   },
   "source": [
    "We can also mask all the entries across the last\n",
    "few axes.\n",
    "If you like, you may even specify\n",
    "to replace such entries with a non-zero value.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = manager.ones(new Shape(2, 3, 4));\n",
    "System.out.println(X.sequenceMask(manager.create(new int[] {1, 2}), -1));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "nvHtehZEmMWE",
    "origin_pos": 24
   },
   "source": [
    "Now we can extend the softmax cross-entropy loss\n",
    "to allow the masking of irrelevant predictions.\n",
    "Initially,\n",
    "masks for all the predicted tokens are set to one.\n",
    "Once the valid length is given,\n",
    "the mask corresponding to any padding token\n",
    "will be cleared to zero.\n",
    "In the end,\n",
    "the loss for all the tokens\n",
    "will be multipled by the mask to filter out\n",
    "irrelevant predictions of padding tokens in the loss.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public class MaskedSoftmaxCELoss extends SoftmaxCrossEntropyLoss {\n",
    "    /* The softmax cross-entropy loss with masks. */\n",
    "\n",
    "    @Override\n",
    "    public NDArray evaluate(NDList labels, NDList predictions) {\n",
    "        NDArray weights = labels.head().onesLike().expandDims(-1).sequenceMask(labels.get(1));\n",
    "        // Remove the states from the labels NDList because otherwise, it will throw an error as SoftmaxCrossEntropyLoss\n",
    "        // expects only one NDArray for label and one NDArray for prediction\n",
    "        labels.remove(1);\n",
    "        return super.evaluate(labels, predictions).mul(weights).mean(new int[] {1});\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FHswBJ5LmMWE",
    "origin_pos": 27
   },
   "source": [
    "For a sanity check, we can create three identical sequences.\n",
    "Then we can\n",
    "specify that the valid lengths of these sequences\n",
    "are 4, 2, and 0, respectively.\n",
    "As a result,\n",
    "the loss of the first sequence\n",
    "should be twice as large as that of the second sequence,\n",
    "while the third sequence should have a zero loss.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Loss loss = new MaskedSoftmaxCELoss();\n",
    "NDList labels = new NDList(manager.ones(new Shape(3, 4)));\n",
    "labels.add(manager.create(new int[] {4, 2, 0}));\n",
    "NDList predictions = new NDList(manager.ones(new Shape(3, 4, 10)));\n",
    "System.out.println(loss.evaluate(labels, predictions));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "w3nwhE0VmMWE",
    "origin_pos": 30
   },
   "source": [
    "## Training\n",
    ":label:`sec_seq2seq_training`\n",
    "\n",
    "In the following training loop,\n",
    "we concatenate the special beginning-of-sequence token\n",
    "and the original output sequence excluding the final token as\n",
    "the input to the decoder, as shown in :numref:`fig_seq2seq`.\n",
    "This is called *teacher forcing* because\n",
    "the original output sequence (token labels) is fed into the decoder.\n",
    "Alternatively,\n",
    "we could also feed the *predicted* token\n",
    "from the previous time step\n",
    "as the current input to the decoder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static void trainSeq2Seq(\n",
    "            EncoderDecoder net,\n",
    "            ArrayDataset dataset,\n",
    "            float lr,\n",
    "            int numEpochs,\n",
    "            Vocab tgtVocab,\n",
    "            Device device)\n",
    "            throws IOException, TranslateException {\n",
    "    Loss loss = new MaskedSoftmaxCELoss();\n",
    "    Tracker lrt = Tracker.fixed(lr);\n",
    "    Optimizer adam = Optimizer.adam().optLearningRateTracker(lrt).build();\n",
    "\n",
    "    DefaultTrainingConfig config =\n",
    "            new DefaultTrainingConfig(loss)\n",
    "                    .optOptimizer(adam) // Optimizer (loss function)\n",
    "                    .optInitializer(new XavierInitializer(), \"\");\n",
    "\n",
    "    Model model = Model.newInstance(\"\");\n",
    "    model.setBlock(net);\n",
    "    Trainer trainer = model.newTrainer(config);\n",
    "\n",
    "    Animator animator = new Animator();\n",
    "    StopWatch watch;\n",
    "    Accumulator metric;\n",
    "    double lossValue = 0, speed = 0;\n",
    "    for (int epoch = 1; epoch <= numEpochs; epoch++) {\n",
    "        watch = new StopWatch();\n",
    "        metric = new Accumulator(2); // Sum of training loss, no. of tokens\n",
    "        try (NDManager childManager = manager.newSubManager(device)) {\n",
    "            // Iterate over dataset\n",
    "            for (Batch batch : dataset.getData(childManager)) {\n",
    "                NDArray X = batch.getData().get(0);\n",
    "                NDArray lenX = batch.getData().get(1);\n",
    "                NDArray Y = batch.getLabels().get(0);\n",
    "                NDArray lenY = batch.getLabels().get(1);\n",
    "\n",
    "                NDArray bos =\n",
    "                        childManager\n",
    "                                .full(new Shape(Y.getShape().get(0)), tgtVocab.getIdx(\"<bos>\"))\n",
    "                                .reshape(-1, 1);\n",
    "                NDArray decInput =\n",
    "                        NDArrays.concat(\n",
    "                                new NDList(bos, Y.get(new NDIndex(\":, :-1\"))),\n",
    "                                1); // Teacher forcing\n",
    "                try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {\n",
    "                    NDArray yHat =\n",
    "                            net.forward(\n",
    "                                            new ParameterStore(manager, false),\n",
    "                                            new NDList(X, decInput, lenX),\n",
    "                                            true)\n",
    "                                    .get(0);\n",
    "                    NDArray l = loss.evaluate(new NDList(Y, lenY), new NDList(yHat));\n",
    "                    gc.backward(l);\n",
    "                    metric.add(new float[] {l.sum().getFloat(), lenY.sum().getLong()});\n",
    "                }\n",
    "                TrainingChapter9.gradClipping(net, 1, childManager);\n",
    "                // Update parameters\n",
    "                trainer.step();\n",
    "            }\n",
    "        }\n",
    "        lossValue = metric.get(0) / metric.get(1);\n",
    "        speed = metric.get(1) / watch.stop();\n",
    "        if ((epoch + 1) % 10 == 0) {\n",
    "            animator.add(epoch + 1, (float) lossValue, \"loss\");\n",
    "            animator.show();\n",
    "        }\n",
    "    }\n",
    "    System.out.format(\n",
    "            \"loss: %.3f, %.1f tokens/sec on %s%n\", lossValue, speed, device.toString());\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "zEyK2Pj1mMWF",
    "origin_pos": 33
   },
   "source": [
    "Now we can create and train an RNN encoder-decoder model\n",
    "for sequence to sequence learning on the machine translation dataset.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int embedSize = 32;\n",
    "int numHiddens = 32;\n",
    "int numLayers = 2;\n",
    "int batchSize = 64;\n",
    "int numSteps = 10;\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 300);\n",
    "\n",
    "float dropout = 0.1f, lr = 0.005f;\n",
    "Device device = Functions.tryGpu(0);\n",
    "\n",
    "Pair<ArrayDataset, Pair<Vocab, Vocab>> dataNMT =\n",
    "        NMT.loadDataNMT(batchSize, numSteps, 600, manager);\n",
    "ArrayDataset dataset = dataNMT.getKey();\n",
    "Vocab srcVocab = dataNMT.getValue().getKey();\n",
    "Vocab tgtVocab = dataNMT.getValue().getValue();\n",
    "\n",
    "encoder = new Seq2SeqEncoder(srcVocab.length(), embedSize, numHiddens, numLayers, dropout);\n",
    "decoder = new Seq2SeqDecoder(tgtVocab.length(), embedSize, numHiddens, numLayers, dropout);\n",
    "\n",
    "EncoderDecoder net = new EncoderDecoder(encoder, decoder);\n",
    "trainSeq2Seq(net, dataset, lr, numEpochs, tgtVocab, device);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZhqzmGf9mMWF",
    "origin_pos": 35
   },
   "source": [
    "## Prediction\n",
    "\n",
    "To predict the output sequence\n",
    "token by token,\n",
    "at each decoder time step\n",
    "the predicted token from the previous\n",
    "time step is fed into the decoder as an input.\n",
    "Similar to training,\n",
    "at the initial time step\n",
    "the beginning-of-sequence (\"&lt;bos&gt;\") token\n",
    "is fed into the decoder.\n",
    "This prediction process\n",
    "is illustrated in :numref:`fig_seq2seq_predict`.\n",
    "When the end-of-sequence (\"&lt;eos&gt;\") token is predicted,\n",
    "the prediction of the output sequence is complete.\n",
    "\n",
    "\n",
    "![Predicting the output sequence token by token using an RNN encoder-decoder.](https://github.com/d2l-ai/d2l-en-colab/blob/master/img/seq2seq-predict.svg?raw=1)\n",
    ":label:`fig_seq2seq_predict`\n",
    "\n",
    "We will introduce different\n",
    "strategies for sequence generation in\n",
    ":numref:`sec_beam-search`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/* Predict for sequence to sequence. */\n",
    "public static Pair<String, ArrayList<NDArray>> predictSeq2Seq(\n",
    "        EncoderDecoder net,\n",
    "        String srcSentence,\n",
    "        Vocab srcVocab,\n",
    "        Vocab tgtVocab,\n",
    "        int numSteps,\n",
    "        Device device,\n",
    "        boolean saveAttentionWeights)\n",
    "        throws IOException, TranslateException {\n",
    "    Integer[] srcTokens =\n",
    "            Stream.concat(\n",
    "                            Arrays.stream(\n",
    "                                    srcVocab.getIdxs(srcSentence.toLowerCase().split(\" \"))),\n",
    "                            Arrays.stream(new Integer[] {srcVocab.getIdx(\"<eos>\")}))\n",
    "                    .toArray(Integer[]::new);\n",
    "    NDArray encValidLen = manager.create(srcTokens.length);\n",
    "    int[] truncateSrcTokens = NMT.truncatePad(srcTokens, numSteps, srcVocab.getIdx(\"<pad>\"));\n",
    "    // Add the batch axis\n",
    "    NDArray encX = manager.create(truncateSrcTokens).expandDims(0);\n",
    "    NDList encOutputs =\n",
    "            net.encoder.forward(\n",
    "                    new ParameterStore(manager, false), new NDList(encX, encValidLen), false);\n",
    "    NDList decState = net.decoder.initState(encOutputs.addAll(new NDList(encValidLen)));\n",
    "    // Add the batch axis\n",
    "    NDArray decX = manager.create(new float[] {tgtVocab.getIdx(\"<bos>\")}).expandDims(0);\n",
    "    ArrayList<Integer> outputSeq = new ArrayList<>();\n",
    "    ArrayList<NDArray> attentionWeightSeq = new ArrayList<>();\n",
    "    for (int i = 0; i < numSteps; i++) {\n",
    "        NDList output =\n",
    "                net.decoder.forward(\n",
    "                        new ParameterStore(manager, false),\n",
    "                        new NDList(decX).addAll(decState),\n",
    "                        false);\n",
    "        NDArray Y = output.get(0);\n",
    "        decState = output.subNDList(1);\n",
    "        // We use the token with the highest prediction likelihood as the input\n",
    "        // of the decoder at the next time step\n",
    "        decX = Y.argMax(2);\n",
    "        int pred = (int) decX.squeeze(0).getLong();\n",
    "        // Save attention weights (to be covered later)\n",
    "        if (saveAttentionWeights) {\n",
    "            attentionWeightSeq.add(net.decoder.attentionWeights);\n",
    "        }\n",
    "        // Once the end-of-sequence token is predicted, the generation of the\n",
    "        // output sequence is complete\n",
    "        if (pred == tgtVocab.getIdx(\"<eos>\")) {\n",
    "            break;\n",
    "        }\n",
    "        outputSeq.add(pred);\n",
    "    }\n",
    "    String outputString =\n",
    "            String.join(\" \", tgtVocab.toTokens(outputSeq).toArray(new String[] {}));\n",
    "    return new Pair<>(outputString, attentionWeightSeq);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "E0f1RCo3mMWF",
    "origin_pos": 38
   },
   "source": [
    "## Evaluation of Predicted Sequences\n",
    "\n",
    "We can evaluate a predicted sequence\n",
    "by comparing it with the\n",
    "label sequence (the ground-truth).\n",
    "BLEU (Bilingual Evaluation Understudy),\n",
    "though originally proposed for evaluating\n",
    "machine translation results :cite:`Papineni.Roukos.Ward.ea.2002`,\n",
    "has been extensively used in measuring\n",
    "the quality of output sequences for different applications.\n",
    "In principle, for any $n$-grams in the predicted sequence,\n",
    "BLEU evaluates whether this $n$-grams appears\n",
    "in the label sequence.\n",
    "\n",
    "Denote by $p_n$\n",
    "the precision of $n$-grams,\n",
    "which is\n",
    "the ratio of\n",
    "the number of matched $n$-grams in\n",
    "the predicted and label sequences\n",
    "to\n",
    "the number of $n$-grams in the predicted sequence.\n",
    "To explain,\n",
    "given a label sequence $A$, $B$, $C$, $D$, $E$, $F$,\n",
    "and a predicted sequence $A$, $B$, $B$, $C$, $D$,\n",
    "we have $p_1 = 4/5$,  $p_2 = 3/4$, $p_3 = 1/3$, and $p_4 = 0$.\n",
    "Besides,\n",
    "let $\\mathrm{len}_{\\text{label}}$ and $\\mathrm{len}_{\\text{pred}}$\n",
    "be\n",
    "the numbers of tokens in the label sequence and the predicted sequence, respectively.\n",
    "Then, BLEU is defined as\n",
    "\n",
    "$$ \\exp\\left(\\min\\left(0, 1 - \\frac{\\mathrm{len}_{\\text{label}}}{\\mathrm{len}_{\\text{pred}}}\\right)\\right) \\prod_{n=1}^k p_n^{1/2^n},$$\n",
    ":eqlabel:`eq_bleu`\n",
    "\n",
    "where $k$ is the longest $n$-grams for matching.\n",
    "\n",
    "Based on the definition of BLEU in :eqref:`eq_bleu`,\n",
    "whenever the predicted sequence is the same as the label sequence, BLEU is 1.\n",
    "Moreover,\n",
    "since matching longer $n$-grams is more difficult,\n",
    "BLEU assigns a greater weight\n",
    "to a longer $n$-gram precision.\n",
    "Specifically, when $p_n$ is fixed,\n",
    "$p_n^{1/2^n}$ increases as $n$ grows (the original paper uses $p_n^{1/n}$).\n",
    "Furthermore,\n",
    "since\n",
    "predicting shorter sequences\n",
    "tends to obtain a higher $p_n$ value,\n",
    "the coefficient before the multiplication term in :eqref:`eq_bleu`\n",
    "penalizes shorter predicted sequences.\n",
    "For example, when $k=2$,\n",
    "given the label sequence $A$, $B$, $C$, $D$, $E$, $F$ and the predicted sequence $A$, $B$,\n",
    "although $p_1 = p_2 = 1$, the penalty factor $\\exp(1-6/2) \\approx 0.14$ lowers the BLEU.\n",
    "\n",
    "We implement the BLEU measure as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/* Compute the BLEU. */\n",
    "public static double bleu(String predSeq, String labelSeq, int k) {\n",
    "    String[] predTokens = predSeq.split(\" \");\n",
    "    String[] labelTokens = labelSeq.split(\" \");\n",
    "    int lenPred = predTokens.length;\n",
    "    int lenLabel = labelTokens.length;\n",
    "    double score = Math.exp(Math.min(0, 1 - lenLabel / lenPred));\n",
    "    for (int n = 1; n < k + 1; n++) {\n",
    "        float numMatches = 0f;\n",
    "        HashMap<String, Integer> labelSubs = new HashMap<>();\n",
    "        for (int i = 0; i < lenLabel - n + 1; i++) {\n",
    "            String key =\n",
    "                    String.join(\" \", Arrays.copyOfRange(labelTokens, i, i + n, String[].class));\n",
    "            labelSubs.put(key, labelSubs.getOrDefault(key, 0) + 1);\n",
    "        }\n",
    "        for (int i = 0; i < lenPred - n + 1; i++) {\n",
    "            String key =\n",
    "                    String.join(\" \", Arrays.copyOfRange(predTokens, i, i + n, String[].class));\n",
    "            if (labelSubs.getOrDefault(key, 0) > 0) {\n",
    "                numMatches += 1;\n",
    "                labelSubs.put(key, labelSubs.getOrDefault(key, 0) - 1);\n",
    "            }\n",
    "        }\n",
    "        score *= Math.pow(numMatches / (lenPred - n + 1), Math.pow(0.5, n));\n",
    "    }\n",
    "    return score;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "BVdTUZgzmMWG",
    "origin_pos": 40
   },
   "source": [
    "In the end,\n",
    "we use the trained RNN encoder-decoder\n",
    "to translate a few English sentences into French\n",
    "and compute the BLEU of the results.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "String[] engs = {\"go .\", \"i lost .\", \"he\\'s calm .\", \"i\\'m home .\"};\n",
    "String[] fras = {\"va !\", \"j\\'ai perdu .\", \"il est calme .\", \"je suis chez moi .\"};\n",
    "for (int i = 0; i < engs.length; i++) {\n",
    "    Pair<String, ArrayList<NDArray>> pair = predictSeq2Seq(net, engs[i], srcVocab, tgtVocab, numSteps, device, false);\n",
    "    String translation = pair.getKey();\n",
    "    ArrayList<NDArray> attentionWeightSeq = pair.getValue();\n",
    "    System.out.format(\"%s => %s, bleu %.3f\\n\", engs[i], translation, bleu(translation, fras[i], 2));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9JiwK1gzmMWG",
    "origin_pos": 42
   },
   "source": [
    "## Summary\n",
    "\n",
    "* Following the design of the encoder-decoder architecture, we can use two RNNs to design a model for sequence to sequence learning.\n",
    "* When implementing the encoder and the decoder, we can use multilayer RNNs.\n",
    "* We can use masks to filter out irrelevant computations, such as when calculating the loss.\n",
    "* In encoder-decoder training, the teacher forcing approach feeds original output sequences (in contrast to predictions) into the decoder.\n",
    "* BLEU is a popular measure for evaluating output sequences by matching $n$-grams between the predicted sequence and the label sequence.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Can you adjust the hyperparameters to improve the translation results?\n",
    "1. Rerun the experiment without using masks in the loss calculation. What results do you observe? Why?\n",
    "1. If the encoder and the decoder differ in the number of layers or the number of hidden units, how can we initialize the hidden state of the decoder?\n",
    "1. In training, replace teacher forcing with feeding the prediction at the previous time step into the decoder. How does this influence the performance?\n",
    "1. Rerun the experiment by replacing GRU with LSTM.\n",
    "1. Are there any other ways to design the output layer of the decoder?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "name": "seq2seq.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
